package com.woniu.owner.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.ResponseData;
import com.woniu.common.ResponseEnum;
import com.woniu.owner.entity.LoginByWeixinForm;
import com.woniu.owner.entity.User;
import com.woniu.owner.service.UserService;
import com.woniu.owner.mapper.UserMapper;
import com.woniu.owner.util.wxutil.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author wudixiaomama
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-01-14 13:54:19
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseData<?> loginByWeixin(LoginByWeixinForm form) {
        log.warn("登录传入的参数为: " + form.toString());
        String wxOpenid = WeixinUtil.getWeiXinOpenid(form.getCode());
        if (wxOpenid != null) {
            User user = userMapper.selectById(wxOpenid);
            if (user == null) { // 没有就注册
                user = new User();
                user.setWxOpenid(wxOpenid);
                user.setName(form.getWxName());
                user.setStatus(true);
                userMapper.insert(user);
            }
            if (!user.getStatus()) { // 检查账号是否冻结
                return new ResponseData<>().fail(ResponseEnum.NO_LOGIN);
            }
            user.setWxAvatar(form.getWxAvatar()); // 微信头像
            userMapper.updateWxAvatar(user.getWxAvatar(), wxOpenid);
            log.info("[通过微信登录] {}", user);
            return new ResponseData<>().ok(user);
        } else {
            return new ResponseData<>().fail(ResponseEnum.LOGIN_ERROR);
        }

    }
}




